import re


class WordDictionary:
    def __init__(self):
        self.search_map = dict()
        self.search_str = ","
        self.add_set = set()
        self.search_dic = dict()

    def addWord(self, word: str) -> None:
        if word not in self.add_set:
            self.add_set.add(word)
            self.search_str += word + ","
            dic = self.search_map
            for s in word:
                if s not in dic:
                    dic[s] = dict()
                dic = dic[s]
            dic[1] = 1
            self.search_dic = dict()

    def search(self, word: str) -> bool:
        if word not in self.search_dic:
            if "." not in word:
                dic = self.search_map
                for s in word:
                    if s not in dic:
                        self.search_dic[word] = False
                        break
                    else:
                        dic = dic[s]
                else:
                    if 1 in dic:
                        self.search_dic[word] = True
                    else:
                        self.search_dic[word] = False
            else:
                re_str = "," + word + ","
                res = re.search(re_str, self.search_str)
                self.search_dic[word] = bool(res)
        return self.search_dic[word]


a = WordDictionary()
a.addWord("bad")
a.addWord("dad")
a.addWord("mad")
print(a.search_map)
print(a.search("pad"))
print(a.search("bad"))